import { NextRequest, NextResponse } from 'next/server'
import { incrementViews, incrementLikes, getLikes, getViews } from '@/lib/index'

// 增加浏览量
export async function POST(request: NextRequest) {
  try {
    const { postId } = await request.json()
    
    if (!postId) {
      return NextResponse.json({ error: '缺少文章ID' }, { status: 400 })
    }
    
    await incrementViews(postId)
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('增加浏览量失败:', error)
    return NextResponse.json({ error: '服务器错误' }, { status: 500 })
  }
}

// 获取浏览量
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const postId = searchParams.get('postId')
    const action = searchParams.get('action')
    
    if (!postId) {
      return NextResponse.json({ error: '缺少文章ID' }, { status: 400 })
    }
    
    if (action === 'views') {
      const views = await getViews(parseInt(postId))
      return NextResponse.json({ views })
    } else if (action === 'likes') {
      const likes = await getLikes(parseInt(postId))
      return NextResponse.json({ likes })
    } else {
      return NextResponse.json({ error: '无效的操作' }, { status: 400 })
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    return NextResponse.json({ error: '服务器错误' }, { status: 500 })
  }
}